﻿/* 
    file: facebookReceiver.js
    require: Utilities.js
*/
etui.ui = etui.ui || {};
!function ($, ns) {
    var uid = 100000;
    function FacebookReceiver() {
        this.callbacks = [];
        this.receiverName;
        this.actions = [];
    }
    var slice = Array.prototype.slice;
    FacebookReceiver.prototype.fireEvent = function () {
        var args = slice.call(arguments);
        for (var n = 0, len = this.callbacks.length; n < len; n++) {
            var callbackObj = this.callbacks[n];
            callbackObj["callback"].apply(callbackObj["context"], args);
        }
    };
    FacebookReceiver.prototype.addEvent = function (callback, context) {
        var obj = {
            "callback": callback,
            "context": context || this
        };
        this.callbacks.push(obj);
    };
    var defaults = {
        receiverName: "facebookReceiver"
    };
    FacebookReceiver.prototype.init = function (options) {
        var settings, len, actions = this.actions;
        settings = $.extend(true, defaults, options);
        this.setReceiverName(settings.receiverName);

        for (len = actions.length; len--; ) {
            var action = actions[len].action;
            var args = actions[len].initArgs;
            action.setReceiverName(this.receiverName);
            action.init.apply(action, args);
            this.addEvent(action.callback, action);
        }
        return this;
    };
    FacebookReceiver.prototype.setReceiverName = function (name) {
        if (!name) {
            // debug 
            // throw "one string parameter requires";
            return;
        }
        name += uid++;
        var namespaces = name.split(".");
        var ns = window;
        for (var n = 0, len = namespaces.length; n < len - 1; n++) {
            ns = ns[namespaces[n]] = ns[namespaces[n]] || {};
        }
        ns[namespaces[n]] = this;
        this.receiverName = name;
    };
    FacebookReceiver.prototype.addAction = function (actionObj /*,[initArguments]*/) {
        var args;
        if (arguments.length > 1) {
            args = slice.call(arguments);
            actionObj = args.shift();
        }
        var obj = {
            action: actionObj,
            initArgs: args
        };
        this.actions.push(obj);
    }
    ns.FacebookReceiver = FacebookReceiver;

} (jQuery, etui.ui);